"""
@File    :   no_introduction.py
@Time    :   2024/03/28 22:25:23
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   无需引入其他业务模块依赖(全局的no_introduction.py下的依赖项不包含在内)的依赖
"""

from typing import Annotated, Literal

from fastapi import Body, Depends
from pydantic import conint
from redis.asyncio import Redis

from src.business.admin.system.oauth2.auth.captcha.utils.image import ImageCaptchaUtil
from src.business.admin.system.oauth2.auth.captcha.utils.sliding_puzzle import (
    SlidingPuzzleCaptchaUtil,
)
from src.config import Settings
from src.dependencies.no_introduction import (
    depend_get_app_settings,
    depend_get_cache_redis_pool,
)
from src.exceptions.custom_async_validator import generate_async_validator_exception


async def depend_validate_and_del_image_captcha(
    code_id: Annotated[str, Body(default=..., min_length=1, max_length=256)],
    code_answer: Annotated[str, Body(default=..., min_length=1, max_length=10)],
    cache_redis_pool: Annotated[Redis, Depends(depend_get_cache_redis_pool)],
) -> bool:
    """验证并在验证成功后删除图像验证码的依赖

    Args:
        code_id (Annotated[str, Body, optional): 图像验证码ID
        code_answer (Annotated[str, Body, optional): 图像验证码ID答案
        cache_redis_pool (Annotated[Redis, Depends): redis连接池

    Returns:
        bool: 验证结果
    """
    result = await ImageCaptchaUtil.validate_and_del_image_captcha(
        cache_redis_pool, code_id, code_answer
    )
    if result is None:
        # 没找到则报图像验证码过期异常
        raise generate_async_validator_exception("code_id", "图像验证码已过期")

    if not result:
        # 答案错误则报图像验证码答案错误异常
        raise generate_async_validator_exception("code_answer", "图像验证码答案错误")
    return True


async def depend_validate_and_del_sliding_captcha(
    code_id: Annotated[
        str, Body(default=..., min_length=1, max_length=256, description="验证码ID")
    ],
    code_answer: Annotated[
        dict[Literal["x", "y"], conint(ge=0)],
        Body(default=..., description="验证码答案"),
    ],
    cache_redis_pool: Annotated[Redis, Depends(depend_get_cache_redis_pool)],
    app_settings: Annotated[Settings, Depends(depend_get_app_settings)],
) -> bool:
    """验证并在验证成功后删除滑块验证码的依赖

    Args:
        cache_redis_pool (Annotated[Redis, Depends): redis连接池
        code_id (Annotated[str, Body, optional): 验证码ID
        code_answer: 验证码答案

    Returns:
        bool: 验证结果
    """
    result = await SlidingPuzzleCaptchaUtil.validate_and_del_sliding_captcha(
        cache_redis_pool,
        code_id,
        code_answer,
        max_error_value=app_settings.sliding_captcha_max_error_value,
    )
    if result is None:
        # 没找到则报滑动验证码过期异常
        raise generate_async_validator_exception("code_answer", "滑动验证码已过期")

    if not result:
        # 答案错误则报滑块验证码验证失败异常
        raise generate_async_validator_exception("code_answer", "滑动验证码验证失败")
    return True
